import java.util.*;

public class 二叉树的右视图 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public List<Integer> ans;
    public List<Integer> rightSideView(TreeNode root) {
        ans = new ArrayList<>();
        dfs(root,0);
        return ans;
    }

    public void dfs(TreeNode root,int pos) {
        if (root == null) {
            return;
        }
        // 很妙的一步, 用长度来判断是否第一次遇到这个节点
        if (pos == ans.size()) {
            ans.add(root.val);
        }
        // 先遍历右树, 再遍历左数
        dfs(root.right,pos + 1);
        dfs(root.left,pos + 1);
    }
}
